using System;
using System.Web.Caching;

namespace Web.Auction.Bid.Extensions
{
    public static class CacheExtension
    {
        public static T Put<T>(this Cache cache, string cacheKey, DateTime absoluteExpiration, Func<T> sourceGetter) where T : class
        {
            return Get(
                (out T cacheData) => {
                    cacheData = cache.Get(cacheKey) as T;
                    return cacheData != null;
                },
                sourceGetter,
                cacheData => cache.Insert(cacheKey, cacheData, null, absoluteExpiration,Cache.NoSlidingExpiration));
        }
        private delegate bool DataGetter<T>(out T data);

        private static T Get<T>(DataGetter<T> dataGetter, Func<T> sourceGetter, Action<T> dataSetter)
        {
            T data;
            if (dataGetter(out data))
            {
                return data;
            }
            data = sourceGetter();
            dataSetter(data);
            return data;
        }

    }
}